package com.ellecity06.common.widgets

import android.content.Context
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.content.res.ResourcesCompat
import com.ellecity06.common.R
import com.ellecity06.common.ktx.dp2px

class ClearEditText @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null) : AppCompatEditText(context, attributeSet) {
    private val clearDrawable: Drawable? by lazy { ResourcesCompat.getDrawable(resources, R.mipmap.icon_black_back, null) }


    override fun onTextChanged(text: CharSequence, start: Int, lengthBefore: Int, lengthAfter: Int) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter)
        setClearIconVisible(hasFocus() && text.isNotEmpty())
    }

    override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect)
        setClearIconVisible(focused && length() > 0)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_UP -> {
                val drawable = compoundDrawables[DRAWABLE_RIGHT]
                if (drawable != null && event.x <= width - paddingRight && event.x >= width - paddingRight - drawable.bounds.width()) {
                    setText("")
                }
            }
        }
        return super.onTouchEvent(event)
    }

    private fun setClearIconVisible(visible: Boolean) {

        setCompoundDrawablesWithIntrinsicBounds(
            compoundDrawables[DRAWABLE_LEFT], compoundDrawables[DRAWABLE_TOP],
            if (visible) clearDrawable else null, compoundDrawables[DRAWABLE_BOTTOM]
        )
        setPadding(paddingLeft, paddingTop, if (paddingRight > 0) paddingRight else context.dp2px(12), paddingBottom)
    }

    companion object {
        private const val DRAWABLE_LEFT = 0
        private const val DRAWABLE_TOP = 1
        private const val DRAWABLE_RIGHT = 2
        private const val DRAWABLE_BOTTOM = 3
    }
}